package cn.wolfcode.tieba.redis.service.impl;

import cn.wolfcode.tieba.domain.User;
import cn.wolfcode.tieba.mapper.UserMapper;
import cn.wolfcode.tieba.redis.service.IUserRedisService;
import cn.wolfcode.tieba.redis.util.RedisKeys;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static cn.wolfcode.tieba.redis.util.RedisKeys.USER_LOGIN_TOKEN;


/**
 * @author 王金龙
 * @date 2021/1/10 18:45
 */
@Service
public class IUserRedisServiceImpl extends ServiceImpl<UserMapper, User> implements IUserRedisService {
    @Autowired
    private StringRedisTemplate template;



    @Override
    public String setLoginToken(User user) {
        String token = UUID.randomUUID().toString().replace("-", "");
        template.opsForValue().set(RedisKeys.join(USER_LOGIN_TOKEN, token), JSON.toJSONString(user),USER_LOGIN_TOKEN.getTime(),TimeUnit.SECONDS);
        return token;
    }

    @Override
    public User getUserToken(String token) {
        String key = RedisKeys.join(USER_LOGIN_TOKEN, token);
        String user = template.opsForValue().get(key);
        if (!StringUtils.hasLength(user)){
            return null;
        }
        template.expire(key, USER_LOGIN_TOKEN.getTime(),TimeUnit.SECONDS);
        return JSON.parseObject(user, User.class);
    }


}
